package com.wsd.common.service;

import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONObject;
import com.wsd.common.entity.UserAccessTokenEntity;
import com.wsd.common.utils.HttpUtils;
import com.wsd.exception.RRException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class QrCodeService {

    @Value("${wx.appId}")
    private String appId;  // 小程序appId

    @Value("${wx.secret}")
    private String secret;  // 小程序秘钥

    @Value("${wx.qrcodeUrl}")
    private String qrcodeUrl;  // 获取跳转二维码的请求地址

    @Value("${wx.tokenUrl}")
    private String tokenUrl;  // 获取access_token的请求地址

    @Value("${wx.env_version}")
    private String envVersion;  // 当前小程序的版本

    /**
     * 获取access_token
     * @return
     */
    public UserAccessTokenEntity getAccessToken() {
        String accessTokenString = HttpUtils.get(tokenUrl + "?grant_type=client_credential&appid=" + appId + "&secret=" + secret);
        UserAccessTokenEntity accessToken = UserAccessTokenEntity.build(accessTokenString);

        if (Objects.isNull(accessToken)) {
            throw new RRException("访问凭证access_token获取失败");
        }

        return accessToken;
    }

    public InputStream generateQtCodeAsStream(String path, String scene) {
        // 获取access_token
        UserAccessTokenEntity accessToken = getAccessToken();
        String accessTokenUrl = qrcodeUrl + "?access_token=" + accessToken.getAccessToken();

        JSONObject params = new JSONObject();
        params.set("scene", scene);
        params.set("path", path);
        params.set("env_version", envVersion);

        HttpResponse response = HttpUtils.post(accessTokenUrl, params.toString());
        if (response.getStatus() == HttpStatus.HTTP_OK) {  // 请求成功
            return response.bodyStream();
        }
        throw new RRException(response.body());
    }

}
